package com.ccdc.cbpc.bigdata.common.util.security;

import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.logging.Level;
@Slf4j
public final class AESUtil {
	private static final String PWD = "Pactera.com";
	private static final String SaltPrefix="E5AF86.";
	private static final String KEY_ALGORITHM = "AES";
	private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法
	static Cipher cipher;
	static KeyGenerator kg ;

	static {
		try {
			cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
			kg = KeyGenerator.getInstance(KEY_ALGORITHM);
		} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
			log.error("初始化异常",e);
		}
	}

	/**
	 * 使用缺省密码进行加密
	 * @param content 明文
	 * @return 密文
	 */
	public static String encryptAsString(String content) {
		return encryptAsString(content, PWD);
	}

	/**
	 * 使用缺省密码进行解密
	 * @param content 密文
	 * @return 明文
	 */
	public static String decryptAsString(String content) {
		return decryptAsString(content, PWD);
	}
	/**加盐加密 主要针对数据源密码处理*/
	public static String encryptSaltAsString(String content){
		//加密过的内容，不再加密
		if(content.startsWith(SaltPrefix)){
			return content;
		}
		String random=System.currentTimeMillis()+"";
		String saltStr =Md5Util.md5(random).toUpperCase().substring(0,12);
		String encrypt =encryptAsString(content,saltStr);
		String fullEncrypt =SaltPrefix+saltStr+encrypt;
		return fullEncrypt;
	}
	/**加盐加密 主要针对数据源密码处理*/
	public static String decryptSaltAsString(String content) {
		if(content!=null && content.startsWith(SaltPrefix) && content.length()>19 ){
			String saltStr =content.substring(0,19);
			String encryptStr =content.substring(19);
			String saltSub =saltStr.replaceFirst(SaltPrefix, "");
			return decryptAsString(encryptStr, saltSub);
		}else{
			return content;
		}
	}

	/**
	 * 加密
	 * @param content 明文
	 * @param password 密码
	 * @return 密文
	 */
	public static String encryptAsString(String content, String password) {
		byte[] encryptResult = encryptAsArray(content, password);
		String encryptResultStr = parseByte2HexStr(encryptResult);
		return encryptResultStr;
	}

	/**
	 * 解密
	 * @param content 密文
	 * @param password 密码
	 * @return 明文
	 */
	public static String decryptAsString(String content, String password) {
		byte[] decryptFrom = parseHexStr2Byte(content);
		byte[] decryptResult = decryptAsArray(decryptFrom,password);
		return new String(decryptResult);
	}

	/**
	 * 加密
	 * @param content 需要加密的内容
	 * @param password 加密密码
	 * @return 密文的byte数组
	 */
	public static byte[] encryptAsArray(String content, String password) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(password.getBytes("GBK"));
			kgen.init(128, secureRandom);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			byte[] byteContent = content.getBytes("utf-8");
			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(byteContent);
			return result; // 加密
		} catch (NoSuchAlgorithmException e) {
			log.error("AES algorithm not found.", e);
		} catch (NoSuchPaddingException e) {
			log.error("Padding scheme of AES not found.", e);
		} catch (InvalidKeyException e) {
			log.error(e.toString());
		} catch (UnsupportedEncodingException e) {
			log.error(e.toString());
		} catch (IllegalBlockSizeException e) {
			log.error(e.toString());
		} catch (BadPaddingException e) {
			log.error(e.toString());
		}
		return null;
	}

	/**
	 * 解密
	 * @param content 待解密内容
	 * @param password 解密密钥
	 * @return 明文的byte数组
	 */
	public static byte[] decryptAsArray(byte[] content, String password) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(password.getBytes("GBK"));
			kgen.init(128, secureRandom);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(content);
			return result; // 加密
		} catch (NoSuchAlgorithmException e) {
			log.error("AES algorithm not found.", e);
		} catch (NoSuchPaddingException e) {
			log.error("Padding scheme of AES not found.", e);
		} catch (InvalidKeyException e) {
			log.error(e.toString());
		} catch (IllegalBlockSizeException e) {
			log.error(e.toString());
		} catch (BadPaddingException e) {
			log.error(e.toString());
		} catch (UnsupportedEncodingException e) {
			log.error(e.toString());
		}
		return null;
	}

	/**
	 * AES 解密操作
	 *
	 * @param content
	 * @param password
	 * @return
	 */
	public static String decrypt(String content, String password) {
		try {
			//使用密钥初始化，设置为解密模式
			cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
			//执行操作
			byte[] result = cipher.doFinal(Base64.decodeBase64(content));
			return new String(result, "utf-8");
		} catch (Exception ex) {
			java.util.logging.Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
		}
		return null;
	}

	/**
	 * 生成加密秘钥
	 *
	 * @return
	 */
	private static SecretKeySpec getSecretKey(final String password) {
		//返回生成指定算法密钥生成器的 KeyGenerator 对象
		//AES 要求密钥长度为 128
		SecureRandom sec = new SecureRandom();
		try {
			sec = SecureRandom.getInstance("SHA1PRNG");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		sec.setSeed(password.getBytes());
		kg.init(128, sec);
		//生成一个密钥
		SecretKey secretKey = kg.generateKey();
		return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥
	}

	/**
	 * 将二进制转换成16进制
	 *
	 * @param buf
	 * @return
	 */
	public static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	/**
	 * 将16进制转换为二进制
	 *
	 * @param hexStr
	 * @return
	 */
	public static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1) {
			return null;
		}
		byte[] result = new byte[hexStr.length() / 2];
		for (int i = 0; i < hexStr.length() / 2; i++) {
			int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}

	public static void main(String[] args) {
//		String str = "jdbc:mysql://ip:3306/XXX?characterEncoding=utf-8&allowMultiQueries=true";
//		String en = encryptAsString(str);
		String en="";
		try {
			en = parseByte2HexStr("密".getBytes("UTF-8"));
			String aesStr=encryptSaltAsString("jdbc:mysql:haracterEncoding=utf-8");
			log.debug(aesStr);
			String desStr =decryptSaltAsString(aesStr);
			log.debug(desStr);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			log.error("测试失败！",e);
		}
		log.debug(en);
	}
}

